package com.lanhai.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
 
 
public class DesUtil {
 
    private final static String DES = "DES";
 
/*    public static void main(String[] args) throws Exception {
        String data = "123 456";
        String key = "abcdefgh";
        System.err.println(encrypt(data, key));
        System.err.println(decrypt(encrypt(data, key), key));
        
        System.out.println(decrypt("JF5dX/TlOg529KAhh+vywjzIp5Msktmf", key));
 
    }*/
 
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
            Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf,key.getBytes());
        return new String(bt);
    }

    /** 
     * <ul> 
     * <li>Description:[根据流得到密钥]</li> 
     * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
     * <li>Midified by [修改人] [修改时间]</li> 
     * </ul> 
     *  
     * @param is 
     * @return 
     */  
    public static Key getKey(InputStream is)  
    {  
        try  
        {  
            ObjectInputStream ois = new ObjectInputStream(is);  
            return (Key) ois.readObject();  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
            throw new RuntimeException(e);  
        }  
    }      

    /** 
     * <ul> 
     * <li>Description:[对数据进行解密]</li> 
     * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
     * <li>Midified by [修改人] [修改时间]</li> 
     * </ul> 
     *  
     * @param key 
     * @param in 
     * @return 
     */  
    public static InputStream doDecrypt(Key key, InputStream in)  
    {  
        try  
        {  
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
            cipher.init(Cipher.DECRYPT_MODE, key);  
            ByteArrayOutputStream bout = new ByteArrayOutputStream();  
            byte[] tmpbuf = new byte[1024];  
            int count = 0;  
            while ((count = in.read(tmpbuf)) != -1)  
            {  
                bout.write(tmpbuf, 0, count);  
                tmpbuf = new byte[1024];  
            }  
            in.close();  
            byte[] orgData = bout.toByteArray();  
            byte[] raw = cipher.doFinal(orgData);  
            ByteArrayInputStream bin = new ByteArrayInputStream(raw);  
            return bin;  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
            throw new RuntimeException(e);  
        }  
    }     
    
    public static void main(String[] args) throws Exception{
    	String keyFilePath = "D:/agvData/key.lm";
    	Key key = getKey(new FileInputStream(keyFilePath));
    	//String strs = "KnRKgodyjf8=";
    	String strs = "YlhQnSy73/PVjViuXtvrDx52uH+fCpC8y62ZORmcgByLjqxlLXd6Q28DZgcAfNeQ";
    	System.out.println(strs);
    	
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(strs);
        byte[] bt2 = decrypt(buf,key);
        String str = new String(bt2);
        String[] sArr = str.split(",");
        for(int i=0; i<sArr.length; i++){
        	System.out.println(sArr[i]);
        }
//    	String file = "D:/agvData/en_param.properties";
//    	FileInputStream fis = new FileInputStream(file); 
//        InputStream raw = doDecrypt(key, fis);  
//        Properties ppt = new Properties();
//        ppt.load(raw);
//        System.out.println(ppt.getProperty("kbExe"));
    }
     
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
   /*     SecureRandom sr = new SecureRandom();*/
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
//        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        cipher.init(Cipher.DECRYPT_MODE, securekey );
        return cipher.doFinal(data);
    }
    
    private static byte[] decrypt(byte[] data, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
        cipher.init(Cipher.DECRYPT_MODE, key);  
        byte[] rd = cipher.doFinal(data); 
        return rd;
    }
    
}